//
//  UserViewController.m
//  KEREN
//
//  Created by MW on 2023/3/10.
//
#import "UserViewController.h"
#import "UserSettingViewController.h"
#import "DeviceCyclingRecordVC.h"
#import "KRGarageViewController.h"
#import "ScanDeviceViewController.h"
#import "KRMessageNoticeViewController.h"
#import "KRRepairReportListVC.h"
#import "KRBurglarizedVC.h"
#import "KeRenUserCell.h"
#import "KeRenUserHeaderView.h"
@interface UserViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *myTable;
@property (nonatomic, strong) UIImageView *userIcon;
@property (nonatomic, strong) NSArray *dataArray;
@end

@implementation UserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setViewLayout];
    [self.view addSubview:[self navBottomViewTag:2]];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    UserInfo *user = USERINFO;
    [_userIcon sd_setImageWithURL:[NSURL URLWithString:user.picture] placeholderImage:[UIImage imageNamed:@"user_default_icon"]];
    self.deviceInfoList = [UserInfoManager sharedInstance].deviceInfoList;
   
    DeviceInfo *deviceInfo = [UserInfoManager sharedInstance].currentDeviceInfo;
    NSMutableArray *array = @[].mutableCopy;
    SmartItem *item;
    if(deviceInfo.deviceConfig.notice){
        item = [SmartItem createSmartItem:@"消息通知" sub_title:@"" imgName:@"uset_notice" type:SmartType_Notice];
        [array addObject:item];
    }
    item = [SmartItem createSmartItem:@"在线报修" sub_title:@"" imgName:@"user_upkeep" type:SmartType_Repair];
    [array addObject:item];
    if(deviceInfo.deviceConfig.report_theft && deviceInfo.is_manager){  //失窃上报仅对车主开放
        item = [SmartItem createSmartItem:@"失窃上报" sub_title:@"失窃上报服务仅对车主开放" imgName:@"burglarized" type:SmartType_Thief];
        [array addObject:item];
    }
    if(deviceInfo.deviceConfig.ride_statistics || deviceInfo.deviceConfig.track_list){
        item = [SmartItem createSmartItem:@"骑行记录" sub_title:@"" imgName:@"user_riding_notes" type:SmartType_Ride_Note];
        [array addObject:item];
    }
    
    item = [SmartItem createSmartItem:@"商城" sub_title:@"" imgName:@"user_shopping" type:SmartType_Shop];
    [array addObject:item];
    item = [SmartItem createSmartItem:@"说明书" sub_title:@"" imgName:@"user_upkeep" type:SmartType_Instruct];
    [array addObject:item];
    self.dataArray = array;
    
    [self.myTable reloadData];
}

-(void)setViewLayout{
    UIImageView *backImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mainBack_image"]];
    backImage.frame = CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT);
    backImage.userInteractionEnabled = YES;
    [self.view addSubview:backImage];
    self.deviceInfoList = [UserInfoManager sharedInstance].deviceInfoList;
    
    UIButton *setBtn = [[UIButton alloc] init];
    [self.view addSubview:setBtn];
    //53
    [setBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(8 + STATUSBAR_HEIGHT);
        make.width.height.offset(40);
        make.right.offset(-24);
    }];
    [setBtn setImage:[UIImage imageNamed:@"user_setting"] forState:UIControlStateNormal];
    [setBtn addTarget:self action:@selector(setBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *bottomBackImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 100 + STATUSBAR_HEIGHT, DEVICE_WIDTH, DEVICE_HEIGHT - 160)];
    bottomBackImageView.image = [UIImage imageNamed:@"user_bottom_back"];
    [self.view addSubview:bottomBackImageView];
    _userIcon = [[UIImageView alloc] init];
    [self.view addSubview:_userIcon];
    [_userIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bottomBackImageView.mas_top).offset(80);
        make.width.height.offset(160);
        make.centerX.equalTo(self.view);
    }];
    UserInfo *user = USERINFO;
    [_userIcon sd_setImageWithURL:[NSURL URLWithString:user.picture] placeholderImage:[UIImage imageNamed:@"user_default_icon"]];
    _userIcon.layer.cornerRadius = 80;
    _userIcon.clipsToBounds = YES;
    
    UIImageView *topImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"KEREN_logo_gray"]];
    [self.view addSubview:topImageView];
    [topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.height.offset(84);
        make.width.offset(360);
        make.centerX.equalTo(self.view);
    }];
    
    _myTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _myTable.dataSource = self;
    _myTable.delegate = self;
    _myTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    _myTable.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_myTable];
    _myTable.tableFooterView = [[UIView alloc] init];
    [_myTable registerNib:[UINib nibWithNibName:@"KeRenUserCell" bundle:nil] forCellReuseIdentifier:@"cellIdentifier"];
    [_myTable registerNib:[UINib nibWithNibName:@"KeRenUserHeaderView" bundle:nil] forHeaderFooterViewReuseIdentifier:@"cellHeaderIdentifier"];
    [_myTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_userIcon.mas_bottom).offset(16);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-70);
    }];
}


-(void)toCycleRecord{
    if([UserInfoManager sharedInstance].deviceInfoList.count == 0){
        [[KRAlartManager shareInstance] showErrorAlert:@"请绑定车辆后再进行操作"];
    }else{
        DeviceCyclingRecordVC *vc = [[DeviceCyclingRecordVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)toNotificeMessage{
    KRMessageNoticeViewController *vc = [[KRMessageNoticeViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)toRepairReport{
    if([UserInfoManager sharedInstance].deviceInfoList.count == 0){
        [[KRAlartManager shareInstance] showErrorAlert:@"请绑定车辆后再进行操作"];
    }else{
        KRRepairReportListVC *vc = [[KRRepairReportListVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)toThiefReport{
    if([UserInfoManager sharedInstance].deviceInfoList.count == 0){
        [[KRAlartManager shareInstance] showErrorAlert:@"请绑定车辆后再进行操作"];
    }else{
        BOOL is_manager = NO;
        for (DeviceInfo *device in [UserInfoManager sharedInstance].deviceInfoList) {
            if(device.is_manager){
                KRBurglarizedVC *vc = [[KRBurglarizedVC alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
                is_manager = YES;
                break;
            }
            is_manager = NO;
        }
        if(!is_manager){
            [[KRAlartManager shareInstance] showAlert:@"该功能仅对车主开放"];
        }
    }
}

-(void)toShop{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://shop.m.jd.com/shop/home?shopId=11979108&utm_source=iosapp"] options:@{} completionHandler:^(BOOL success) {
    }];
}

-(void)toInstruct{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://%@/html/instructionManual/Ios.html",BaseHost]] options:@{} completionHandler:^(BOOL success) {
    }];
}

- (void)setBtnClick{
    UserSettingViewController *vc = [[UserSettingViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark- UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 72.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return UITableViewAutomaticDimension;
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    KeRenUserHeaderView *headerV = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"cellHeaderIdentifier"];
    UserInfo *user = USERINFO;
    NSString *photoStr = [user.phone stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    headerV.userLb.text = photoStr;
    [headerV setDataSource:self.deviceInfoList];
    return headerV;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = [UIColor clearColor];
    return v;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SmartItem *item = self.dataArray[indexPath.row];
    if(item.type == SmartType_Notice){
        [self toNotificeMessage];
    }else if(item.type == SmartType_Repair){
        [self toRepairReport];
    }else if(item.type == SmartType_Thief){
        [self toThiefReport];
    }else if(item.type == SmartType_Ride_Note){
        [self toCycleRecord];
    }else if(item.type == SmartType_Shop){
        [self toShop];
    }else if(item.type == SmartType_Instruct){
        [self toInstruct];
    }
}

#pragma mark- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KeRenUserCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    cell.backgroundColor = [UIColor clearColor];
    cell.bgV.layer.cornerRadius = 25;
    SmartItem *item = self.dataArray[indexPath.row];
    if(item.type == SmartType_Thief){
        [cell setUserCellStyle:UserCellStyle_SubTitle];
    }else{
        [cell setUserCellStyle:UserCellStyle_Common];
    }
    cell.imgV.image = [UIImage imageNamed:item.imgName];
    cell.titleLb.text = item.title;
    cell.subTitleLb.text = item.sub_title;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

@end
